package crp.core.resource.domain.services;

import com.qwlabs.lang.C2;
import com.qwlabs.panache.Ranged;
import crp.core.resource.domain.models.CourseResourceEntity;
import crp.core.resource.domain.models.ResourceEntity;
import crp.core.resource.domain.models.ResourceQuery;
import crp.core.resource.domain.repositories.CourseResourceRepository;
import crp.core.resource.domain.repositories.ResourceRepository;
import io.quarkus.panache.common.Range;

import javax.enterprise.context.ApplicationScoped;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Stream;

@ApplicationScoped
public class CourseResourceSearcher {
    private final CourseResourceRepository courseResourceRepository;
    private final ResourceRepository resourceRepository;

    public CourseResourceSearcher(CourseResourceRepository courseResourceRepository,
                                  ResourceRepository resourceRepository) {
        this.courseResourceRepository = courseResourceRepository;
        this.resourceRepository = resourceRepository;
    }

    public Ranged<CourseResourceEntity> by(String courseId, Range range) {
        return Ranged.of(courseResourceRepository.findByCourseId(courseId), range);
    }

    public Stream<CourseResourceEntity> by(Set<String> courseIds, ResourceQuery filter) {
        Collection<String> resourceIds = C2.set(resourceRepository.find(filter), ResourceEntity::getId);
        return courseResourceRepository.findByCourseIdsAndResourceIds(courseIds, resourceIds);
    }

    public Stream<CourseResourceEntity> byResourceIds(Collection<String> resourceIds) {
        return courseResourceRepository.findByResourceIds(resourceIds);
    }
}
